package com.yuanjun.product.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yuanjun.product.vo.base.BaseResult;
import com.yuanjun.product.vo.common.Const;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 *  zsc.
 */
@Slf4j
public class SecurityCheckInterceptor extends HandlerInterceptorAdapter {
    @Value("${spring.profiles.active}")
    String profile;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        log.info("pre拦截到：{}", requestURI);
        if (method.equalsIgnoreCase("OPTIONS") || isCheckUri(requestURI)) {
            return true;
        }
        if(requestURI.contains("/error")){
            BaseResult res = BaseResult.createFail(Const.HttpRespCode.TOKEN_INVALID, "系统异常，请稍后重试。");
            dealErrorReturn(request, response, res);
            return false;
        }
        String token = !StringUtils.isEmpty(request.getHeader(Const.PROFRONTTOKEN)) ? request.getHeader(Const.PROFRONTTOKEN) : request.getHeader(Const.PROADMINTOKEN);
        log.info("----token----:{}", token);
        if (StringUtils.isEmpty(token)) {
            BaseResult res = BaseResult.createFail(Const.HttpRespCode.TOKEN_INVALID, "token为空");
            dealErrorReturn(request, response, res);
            return false;
        }
        String tokenJson = stringRedisTemplate.opsForValue().get(token);
        if (StringUtils.isEmpty(tokenJson)) {
            log.info("token失效");
            BaseResult res = BaseResult.createFail(Const.HttpRespCode.TOKEN_INVALID, "登录过期,请重新登录");
            dealErrorReturn(request, response, res);
            return false;
        }
        stringRedisTemplate.opsForValue().set(token, tokenJson, 3600, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

    public void dealErrorReturn(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object obj) {
        String json = JSONObject.toJSONString(obj);
        PrintWriter writer = null;
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("text/html; charset=utf-8");
        try {
            writer = httpServletResponse.getWriter();
            writer.print(json);

        } catch (IOException ex) {

        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    private boolean isCheckUri(String requestURI) {
        return requestURI.contains("/home/") || requestURI.contains("/userLogin/") || requestURI.contains("/sms/")
                || requestURI.contains("/product/productList") || requestURI.contains("/product/productDetail");
    }
}
